package com.qf.springboot2203_02.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.qf.springboot2203_02.dao.UserDao;
import com.qf.springboot2203_02.entity.User;
import com.qf.springboot2203_02.service.UserService;
import com.qf.springboot2203_02.vo.ResultVo;
import com.qf.springboot2203_02.vo.UserResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Value("${user.filepath}")
    String filepath;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    UserDao userDao;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVo login(String username, String password) {
        String md5password = DigestUtil.md5Hex(password);
        User user = userDao.login(username, md5password);
        if (user != null) {
            return ResultVo.ok();
        } else {
            return ResultVo.error("用户名或密码错误");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo getRegist(UserResultVo userResultVo) throws IOException {
        String filename = UUID.randomUUID() + "_" + userResultVo.getPhotopath().getOriginalFilename();
        String finalFilepath = filepath + filename;
        userResultVo.getPhotopath().transferTo(new File(finalFilepath));
        String md5password = DigestUtil.md5Hex(userResultVo.getPassword());
        User user = new User(null, userResultVo.getName(), md5password, userResultVo.getSex(), userResultVo.getBirthday()
                , new Date(), filename);
        int index = userDao.insertRegist(user);
        if (index != 0) {
            return ResultVo.ok();
        } else {
            return ResultVo.error("注册失败");
        }

    }
}
